import remoteSearchProductInput from '../remote-search-product-input';
import remoteSearchEmpInput from '../remote-search-emp-input';
import remoteSearchCustomerInput from '../remote-search-customer-input';
import remoteSearchColorNumberInput from '../remote-search-color-number-input';
import { spinSpecPathPage } from '../../../../../api/technology/route';
import { systemBusinessDictPage } from '@/api/basicData/businessDict';

import {
    productionPrdOrderCheckExists,
    productionPrdOrderCreate,
    productionPrdOrderGet,
    productionPrdOrderUpdate,
    productionSaleOrderGetIds,
    productionTestProductConfigPage
} from '../../../../../api/production/order';
import { formatDate, tipsBar } from '../../../../../utils/jk/jk-tool';
import {
    validateArr,
    validateNormal,
    validateNull
} from '../../../../../utils/jk/validator';
import {
    mathJsAdd,
    mathJsDiv,
    mathJsSub
} from '../../../../../utils/jk/jk-cals';
import { spinVarietyYarnSpecPage } from '../../../../../api/technology/yarnSeedTechnology';
import remoteSearchBatchCodeInput from '../../../qhPrd/productConfigCotton/components/remote-search-batch-code-input';
import checkboxPopover from './checkbox-popover';

import noticeListPopoverBar from '../notice-list-popover-bar';
import frontNoticePopoverBar from '../front-notice-popover-bar';
import {
    orderPriorityList,
    spinTypeList,
    orderStateList,
    directionTwistList
} from '../../../../../utils/jk/status-option-list';
import orderBatchList from './order-batch-list';
import addQtyDialog from './add-qty-dialog';
import handlerCache from '../../../../../mixins/handler-cache';
import saleOrderList from '../saleOrderList/index';
import saleOrderMx from '../saleOrderList/mx';
import supplementaryPlanMx from './supplementaryPlanMx';
import batchItemMaterialList from './batch-item-material-list';

import showExistMachineTaskDialog from '../show-exist-machine-task-dialog.vue';
export default {
    mixins: [handlerCache, saleOrderMx, supplementaryPlanMx],
    components: {
        showExistMachineTaskDialog,
        saleOrderList,
        addQtyDialog,
        orderBatchList,
        frontNoticePopoverBar,
        noticeListPopoverBar,
        remoteSearchColorNumberInput,
        checkboxPopover,
        remoteSearchProductInput,
        remoteSearchEmpInput,
        remoteSearchBatchCodeInput,
        remoteSearchCustomerInput,
        batchItemMaterialList
    },
    props: {
        loading: {
            type: Boolean,
            default: false
        },
        pageType: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            apiItem: {
                save: productionPrdOrderCreate,
                update: productionPrdOrderUpdate
            },
            batchTabActive: '0',
            isDemoYarn: false,
            demoYarnInfo: null,
            showContentLoading: false,
            orderStateList: orderStateList,
            addQtyDialogState: false,
            childTabActive: '0',
            activeTab: '0',
            tableData: [],
            priorityList: orderPriorityList,
            spinTypeList: spinTypeList,
            saveBtnLoading: false,
            workshopList: [],
            dataId: null,
            saveDialogState: false,
            varietyYarnSpecList: [],
            spinSpecPathList: [],
            colorList: [],
            directionTwistList: directionTwistList,
            ruleForm: {
                code: '',
                typeSpinning: undefined,
                productOrderBatchList: [],
                colorId: null,
                colorName: '',
                ifTest: false,
                saleQty: 0,
                inventoryQty: 0,
                yarnType: '',
                tenPrice: null,
                yarnCount: null,
                warningPercentage: 85,
                specialProcessesList: [
                    { name: '链轮', value: '' },
                    { name: '氨纶倍数', value: '' },
                    { name: '细纱捻度', value: '' },
                    { name: '实纺支数', value: '' },
                    { name: '并线捻度', value: '' }
                ],
                labelColorList: [],
                coarseSandList: [],
                gramWeight: null,
                meters: null,
                varietyYarnSpecId: null,
                varietyYarnSpecName: '',
                specSheetId: null,
                specSheetCode: '',
                varietyYarnSpecRemark: '',
                billTypeCode: '',
                billTypeId: null,
                billTypeName: '',
                coefficient: null,
                completionQty: null,
                customerInformation: '',
                dailySupplyQty: null,
                deliveryDateFrom: '',
                deliveryDateTo: '',
                ifCotton: true,
                ifNoticeChange: true,
                ifPackReport: true,
                ifSpec: true,
                orderDate: '',
                planProcessCode: '',
                planProcessId: null,
                planProcessName: '',
                plannerId: null,
                plannerName: '',
                priorityId: 0,
                priorityName: '',
                processCode: '',
                processId: null,
                processName: '',
                productCode: '',
                productId: null,
                productModels: '',
                productName: '',
                productTypeId: null,
                productTypeName: '',
                orderQty: null,
                purposeId: null,
                purposeName: '',
                qualityRequirement: '',
                relationCode: '',
                remark: '',
                serviceState: 0,
                specPathCode: '',
                specPathId: null,
                specPathName: '',
                stockTypeId: null,
                stockTypeName: '',
                techRequirement: '',
                technologyId: null,
                technologyName: '',
                twistDirectionId: null,
                twistDirectionName: '',
                unitCode: '',
                unitId: null,
                unitName: '',
                workshopId: null,
                workshopName: '',
                customerName: '',
                customerId: null,
                customerCode: '',
                batchId: null,
                batchCode: '',
                shipmentsQty: null,
                productOrderSaleList: []
            },
            rules: {
                productOrderBatchList: [
                    {
                        required: true,
                        validator: validateArr,
                        trigger: 'change'
                    }
                ],
                warningPercentage: [{ required: true, trigger: 'change' }],
                colorId: [{ required: true, trigger: 'change' }],
                shipmentsQty: [{ required: true, trigger: 'change' }],
                yarnCount: [{ required: true, trigger: 'change' }],
                orderDate: [{ required: true, trigger: 'change' }],
                specSheetId: [{ required: true, trigger: 'change' }],
                saleQty: [
                    {
                        required: true,
                        validator: validateNormal,
                        trigger: 'change'
                    }
                ],
                deliveryDateTo: [
                    {
                        required: true,
                        validator: validateNormal,
                        trigger: 'change'
                    }
                ],
                deliveryDateFrom: [
                    {
                        required: true,
                        validator: validateNormal,
                        trigger: 'change'
                    }
                ],
                dailySupplyQty: [
                    {
                        required: true,
                        validator: validateNormal,
                        trigger: 'change'
                    }
                ],
                priorityId: [
                    {
                        required: true,
                        validator: validateNull,
                        trigger: 'change'
                    }
                ],
                plannerId: [
                    {
                        required: true,
                        validator: validateNormal,
                        trigger: 'change'
                    }
                ],
                meters: [{ required: true, trigger: 'change' }],
                moistureRegain: [{ required: true, trigger: 'change' }],
                gramWeight: [{ required: true, trigger: 'change' }],
                fixedLength: [{ required: true, trigger: 'change' }],
                efficiencyPercent: [{ required: true, trigger: 'change' }],
                dailyYield: [{ required: true, trigger: 'change' }],
                batchId: [{ required: true, trigger: 'change' }],
                productName: [
                    {
                        required: true,
                        validator: validateNormal,
                        trigger: 'change'
                    }
                ]
            },
            showExistMachineTaskDialogState: false,
            existsTaskList: []
        };
    },
    methods: {
        // 设置 ruleForm 中的字段
        setFormFields(target, source, fields) {
            fields.forEach((key) => {
                this.$set(target, key, source[key]);
            });
        },
        onSelectBatchChangeOfRowItem(e) {
            this.$set(this.ruleForm, 'batchId', e.id);
            this.$set(this.ruleForm, 'batchCode', e.batchCode);
        },
        getTypeListRequest() {
            return systemBusinessDictPage({ categoryCode: 'COLOR_TYPE' }).then(
                (res) => {
                    if (res.data.status === 200) {
                        this.colorList = res.data.res;
                    }
                }
            );
        },
        updateDataOfMaterialList(e, index) {
            // console.log(index, e, '----');
            const { totalQuantity, productOrderElementItemLists } = e;
            this.$set(this.ruleForm, 'totalQuantity', totalQuantity);
            this.$set(
                this.ruleForm,
                'productOrderElementItemLists',
                productOrderElementItemLists
            );
        },
        getSpinSpecPathListRequest() {
            return spinSpecPathPage({ auditState: 1 }).then((res) => {
                if (res.data.status === 200) {
                    // this.spinSpecPathList = res.data.res || [];
                    this.spinSpecPathList = [
                        { id: 0, name: '路线一' },
                        { id: 1, name: '路线二' }
                    ];
                }
            });
        },
        onConfirmBtn() {
            this.$refs['ruleForm'].validate((valid) => {
                if (valid) {
                    let isOk = true;
                    // debugger;
                    // 小于15公斤时，纸管、腰绳、标签颜色不必填，否则必填
                    if (this.isDemoYarn) {
                        this.validatorMachineTaskIsExists();
                    } else {
                        isOk = this.ruleForm.productOrderBatchList.every(
                            (x) =>
                                x.orderBatchPrdNotice.paperTubeList &&
                                x.orderBatchPrdNotice.paperTubeList.length &&
                                x.waistPopeList &&
                                x.waistPopeList.length &&
                                x.labelColorList &&
                                x.labelColorList.length
                        );
                        if (isOk) {
                            this.validatorMachineTaskIsExists();
                        } else {
                            this.$tipsBar(
                                this,
                                'custom',
                                'warning',
                                '纸管、腰绳、标签颜色不能为空!'
                            );
                        }
                    }
                } else {
                    this.$tipsBar(this, 'validator');
                }
            });
        },
        // 验证任务是否存在，同品种+批号+机台+未了机的任务
        validatorMachineTaskIsExists() {
            this.saveBtnLoading = true;
            this.showContentLoading = true;
            const { valid, errors } =
                this.$refs.materialList.validateBeforeSubmit();
            if (this.ruleForm.productOrderElementItemLists.length > 0 && !valid) {
                this.$tipsBar(this, 'custom', 'warning', errors.join(' ; '));
                this.saveBtnLoading = false;
                this.showContentLoading = false;
                return;
            }
            this.createAndUpdateRequest();

            // productionPrdOrderCheckExists(this.getParamData()).then((res) => {
            //     if (res.data.status === 200) {
            //         // 有返回值说明当前机台存在同品种、批号的任务，需展示给用户
            //         if (res.data.res && res.data.res.length) {
            //             // if (res.data.res) {
            //             this.existsTaskList = res.data.res || [];
            //             this.showExistMachineTaskDialogState = true;
            //             this.saveBtnLoading = false;
            //             this.showContentLoading = false;
            //         } else {
            //             this.createAndUpdateRequest();
            //         }
            //     }
            // });
        },
        createAndUpdateRequest() {
            this.saveBtnLoading = true;
            this.showContentLoading = true;
            // console.log(this.getParamData(), 'this.getParamData()');
            // return;
            const api = !this.ruleForm.id
                ? productionPrdOrderCreate
                : productionPrdOrderUpdate;
            api(this.getParamData()).then((res) => {
                this.saveBtnLoading = false;
                this.showContentLoading = false;
                if (res.data.status === 200) {
                    this.getErrorInfoRequest({ state: 0 });
                    if (!this.ruleForm.id) {
                        this.onJump(res.data.res);
                    } else {
                        // 移除地址栏多余参数(只要用于：销售订单下达至已有订单，保存后又希望删除该销售订单，却删不掉的问题)
                        this.$toOtherRouter({
                            name: 'editPrdOrder',
                            query: {
                                id: this.ruleForm.id
                            }
                        });
                        this.getDependentData();
                    }
                }
            });
        },
        onFinishOfShowExistMachineTaskDialogState() {
            this.showExistMachineTaskDialogState = false;
            this.createAndUpdateRequest();
        },
        onVisibleChangeOfShowExistMachineTaskDialogState(e) {
            this.showExistMachineTaskDialogState = e;
        },
        onSaleOrderChange(data) {
            this.$set(this.ruleForm, 'productOrderSaleList', data);
            if (data && data.length) {
                let productInfo = data[0] || {};
                productInfo = {
                    productId: productInfo.productId,
                    productCode: productInfo.productCode,
                    productName: productInfo.productName,
                    productModels: productInfo.productModels,
                    unitId: productInfo.unitId,
                    unitCode: productInfo.unitCode,
                    unitName: productInfo.unitName,
                    yarnCount: productInfo.yarnCount
                };
                if (
                    !this.ruleForm.productId ||
                    this.ruleForm.productId !== data[0].productId
                ) {
                    this.setProductDependentData(productInfo);
                }

                /**
                 * 未完成的批号只有一个时，将剩余的量(减去已完成批号的量)，给到该批号
                 * */
                // 计算未完成的批号个数
                let count = 0;
                this.ruleForm.productOrderBatchList.forEach((x) => {
                    if (
                        !x.orderBatchPrdNotice.auditState ||
                        x.orderBatchPrdNotice.auditState <= 2
                    ) {
                        count++;
                    }
                });
                // 只有一个批号时
                if (count === 1) {
                    // 销售订单总共下达的量
                    let totalVal = 0;
                    this.ruleForm.productOrderSaleList.forEach((x) => {
                        totalVal = mathJsAdd(
                            totalVal,
                            x.orderAllocatedQty || 0
                        );
                    });
                    let val = totalVal;
                    // 减掉已完成批号的量
                    this.ruleForm.productOrderBatchList.forEach((x) => {
                        if (x.orderBatchPrdNotice.auditState === 3) {
                            val = mathJsSub(
                                val,
                                x.orderBatchPrdNotice.productionQty || 0
                            );
                        }
                    });
                    this.ruleForm.productOrderBatchList.forEach((x) => {
                        if (
                            !x.orderBatchPrdNotice.auditState ||
                            x.orderBatchPrdNotice.auditState >= 2
                        ) {
                            this.$set(
                                x.orderBatchPrdNotice,
                                'productionQty',
                                val
                            );
                        }
                    });
                }
                this.calSaleOrderTotalQty();
            }
        },
        // 销售数量的值计算
        calSaleOrderTotalQty() {
            let num = 0;
            this.ruleForm.productOrderSaleList.forEach((x) => {
                num = mathJsAdd(x.orderAllocatedQty || 0, num); // 原来用的是下达数量相加
                // num = mathJsAdd(x.productQty || 0, num); // 现在用销售数量相加
            });
            this.$set(this.ruleForm, 'saleQty', num);
            this.calOrderQty();
        },
        onFinishOfAddQtyDialog() {
            this.addQtyDialogState = false;
            this.getDetailRequest();
        },
        onVisibleChangeOfAddQtyDialogState(e) {
            this.addQtyDialogState = e;
        },
        onAddQtyBtn() {
            this.addQtyDialogState = true;
        },
        onCreateFrontPlanBtn() {},
        onPrintBtn() {
            const routeUrl = this.$router.resolve({
                name: 'printOrder',
                query: {
                    id: this.ruleForm.id
                }
            });

            window.open(routeUrl.href, '_blank');
        },
        onSelectColorNumberChange(e) {
            const findVal = this.colorList.find((item) => item.code === e);
            this.$set(this.ruleForm, 'colorCode', e);
            this.$set(this.ruleForm, 'colorName', findVal.name);
            this.$set(this.ruleForm, 'colorId', findVal.id);
        },
        defaultCsRowData() {
            return {
                name: '',
                value: ''
            };
        },
        defaultRowData() {
            return {
                name: '',
                value: ''
            };
        },
        onJumpList() {
            this.$store.dispatch('tagsView/delView', {
                path: this.$route.path
            });
            this.$toMainRouter({
                name: 'PrdOrder'
            });
        },
        onJump(id) {
            this.$store.dispatch('tagsView/delView', {
                path: this.$route.path
            });
            this.$toOtherRouter({
                name: 'editPrdOrder',
                query: {
                    id: id
                }
            });
        },
        onRemoveBtn(scope) {
            this.ruleForm.specialProcessesList.splice(scope.rowIndex, 1);
        },
        onAddBtn() {
            this.ruleForm.specialProcessesList.push(this.defaultRowData());
        },
        onSelectBatchChange(e) {
            if (Object.keys(e).length) {
                this.$set(this.ruleForm, 'batchId', e.id);
                this.$set(this.ruleForm, 'batchCode', e.batchCode);
            }
        },
        // 生产数量
        calOrderQty() {
            // 销售订单减去库存数量
            const val = mathJsSub(
                this.ruleForm.saleQty || 0,
                this.ruleForm.inventoryQty || 0
            );
            // TODO: 2025.03.28 实施那边要求销售数量和生产数量都是销售订单中的本次下达数里总和
            // const val = this.ruleForm.saleQty || 0;
            this.$set(this.ruleForm, 'orderQty', val);
            // 修改通知单的排产数量
            if (this.ruleForm.productOrderBatchList) {
                this.ruleForm.productOrderBatchList.forEach((x) => {
                    // 只能修改已完成以外的通知单
                    if (x.orderBatchPrdNotice.auditState !== 3) {
                        // this.$set(x.orderBatchPrdNotice, 'productionQty', val);
                    }
                });
            }
        },
        calDailySupplyQty(type) {
            if (type === 'deliveryDateTo') {
                if (
                    this.ruleForm.deliveryDateFrom &&
                    this.ruleForm.deliveryDateTo <
                        this.ruleForm.deliveryDateFrom
                ) {
                    tipsBar(
                        this,
                        'custom',
                        'warning',
                        '交货结束时间不能早于开始时间!'
                    );
                    this.$set(this.ruleForm, 'deliveryDateTo', '');
                }
            }
            if (type === 'deliveryDateFrom') {
                if (
                    this.ruleForm.deliveryDateTo &&
                    this.ruleForm.deliveryDateFrom >
                        this.ruleForm.deliveryDateTo
                ) {
                    tipsBar(
                        this,
                        'custom',
                        'warning',
                        '交货开始时间不能晚于结束时间!'
                    );
                    this.$set(this.ruleForm, 'deliveryDateFrom', '');
                }
            }
            if (
                this.ruleForm.orderQty &&
                this.ruleForm.deliveryDateFrom &&
                this.ruleForm.deliveryDateTo
            ) {
                if (!this.ruleForm.orderQty) {
                    this.ruleForm.dailySupplyQty = 0;
                } else {
                    if (type === 'dailySupplyQty') {
                        // 改变日供货量 求 计划结束时间 = 订单数量/日供货量 + 计划开始时间
                        this.ruleForm.deliveryDateTo =
                            this.transferCouponValueTime(
                                this.ruleForm.deliveryDateFrom,
                                Math.floor(
                                    mathJsDiv(
                                        this.ruleForm.orderQty,
                                        this.ruleForm.dailySupplyQty
                                    )
                                )
                            );
                    } else if (type === 'deliveryDateTo') {
                        // 改变计划结束时间  求 日供货量 = 订单数量 / (计划结束时间-计划开始时间)
                        this.ruleForm.dailySupplyQty = Math.floor(
                            mathJsDiv(
                                this.ruleForm.orderQty,
                                this.dateDiff(
                                    this.ruleForm.deliveryDateTo,
                                    this.ruleForm.deliveryDateFrom
                                )
                            )
                        );
                    } else if (type === 'deliveryDateFrom') {
                        // 改变计划结束时间  求 日供货量 = 订单数量 / (计划结束时间-计划开始时间)
                        this.ruleForm.dailySupplyQty = Math.floor(
                            mathJsDiv(
                                this.ruleForm.orderQty,
                                this.dateDiff(
                                    this.ruleForm.deliveryDateTo,
                                    this.ruleForm.deliveryDateFrom
                                )
                            )
                        );
                    } else if (type === 'orderQty') {
                        // 改变订单数量  求 日供货量 = 订单数量 / (计划结束时间-计划开始时间)
                        if (this.ruleForm.orderQty === 0) {
                            this.ruleForm.dailySupplyQty = 0;
                        } else {
                            this.ruleForm.dailySupplyQty = Math.floor(
                                mathJsDiv(
                                    this.ruleForm.orderQty,
                                    this.dateDiff(
                                        this.ruleForm.deliveryDateTo,
                                        this.ruleForm.deliveryDateFrom
                                    )
                                )
                            );
                        }
                    }
                }
            } else {
                this.$set(this.ruleForm, 'dailySupplyQty', 0);
            }
        },
        dateDiff(sDate1, sDate2) {
            const d1 = Date.parse(sDate1);
            const d2 = Date.parse(sDate2);
            const diff = Math.abs(d2 - d1);
            // 差的毫秒 / 一天的毫秒
            const days = Math.ceil(diff / 24 / 60 / 60 / 1000) + 1;
            return days;
        },
        // 计算结束时间
        transferCouponValueTime(startDate, valueTime) {
            // startDate 开始时间  ， valueTime  有效天数
            const filZero = (n) => (n < 10 ? '0' + n : '' + n);
            const date = new Date(startDate);
            const newDate = new Date(
                date.getFullYear(),
                date.getMonth(),
                date.getDate() + valueTime
            );
            const year = newDate.getFullYear();
            const month = newDate.getMonth() + 1;
            const day = newDate.getDate();
            const dataTime = year + '-' + filZero(month) + '-' + filZero(day);
            return dataTime;
        },
        onSelectEmpChange(e) {
            if (Object.keys(e).length) {
                this.$set(this.ruleForm, 'plannerId', e.id);
                this.$set(this.ruleForm, 'plannerName', e.name);
            }
        },
        onSelectCustomerChange(e) {
            if (Object.keys(e).length) {
                this.$set(this.ruleForm, 'customerId', e.id);
                this.$set(this.ruleForm, 'customerName', e.name);
            }
        },
        onSelectProductChange(e) {
            console.log(e, '----');
            if (e && Object.keys(e).length) {
                const item = {
                    productId: e.id,
                    productCode: e.code,
                    productName: e.name,
                    productModels: e.models,
                    unitId: e.unitId,
                    unitCode: e.unitCode,
                    unitName: e.unitName,
                    yarnCount: e.yarnCount,
                    categoryId: e.categoryId,
                    categoryCode: e.categoryCode,
                    categoryName: e.categoryName
                };
                this.setProductDependentData(item);
            }
        },
        setProductDependentData(e) {
            this.setFormFields(this.ruleForm, e, [
                'productId',
                'productCode',
                'productName',
                'productModels',
                'unitId',
                'unitCode',
                'unitName',
                'categoryId',
                'categoryCode',
                'categoryName'
            ]);
            this.$set(
                this.ruleForm,
                'yarnCount',
                e.yarnCount ? Number(e.yarnCount) : 0
            );
        },
        onProcessChange() {
            this.getTechnologyItemListRequest();
        },
        onSelectBatchCodeChange(e) {
            if (Object.keys(e).length) {
                this.$set(this.ruleForm, 'batchCode', e.batchCode);
            }
        },
        getParamData() {
            const params = JSON.parse(JSON.stringify(this.ruleForm));
            if (!this.ruleForm.id) delete params.id;
            if (params.varietyYarnSpecId) {
                params.varietyYarnSpecName = this.varietyYarnSpecList.find(
                    (x) => x.id === params.varietyYarnSpecId
                ).name;
            }
            params.varietyYarnSpecItemList = this.tableData.map((x) => x);
            if (params.priorityId || params.priorityId === 0) {
                const priorityItem =
                    this.priorityList.find((x) => x.id === params.priorityId) ||
                    {};
                params.priorityName = priorityItem.name;
            }
            if (params.workshopId) {
                params.workshopName = this.workshopList.find(
                    (x) => x.id === params.workshopId
                ).name;
            }
            // TODO:工艺路线的参数
            const spinSpecPathItem =
                this.spinSpecPathList.find(
                    (x) => x.id === this.ruleForm.spinSpecPathId
                ) || {};
            params.spinSpecPathCode = spinSpecPathItem.code;
            params.spinSpecPathName = spinSpecPathItem.name;

            return params;
        },
        onVisibleChange(e) {
            this.$emit('on-visible-change', e);
            if (!e) {
                Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.$refs.ruleForm.resetFields();
                });
            }
        },
        onCopyBtn() {
            this.$toOtherRouter({
                name: 'addPrdOrder',
                query: {
                    id: this.ruleForm.id,
                    isCopy: '1'
                }
            });
        },
        getDetailRequest() {
            return productionPrdOrderGet({ id: this.$route.query.id }).then(
                (res) => {
                    this.showContentLoading = false;
                    if (res.data.status === 200) {
                        const resData = JSON.parse(
                            JSON.stringify(res.data.res)
                        );
                        // 复制时，移除id
                        if (this.$route.query.isCopy === '1') {
                            resData.code = '';
                            resData.auditState = null;
                            resData.shipmentsQty = 0;
                            resData.productOrderBatchList.forEach((x) => {
                                delete x.id;
                                x.coarseSandList.forEach((x) => {
                                    delete x.id;
                                });
                            });
                            resData.varietyYarnSpecItemList.forEach((x) => {
                                delete x.id;
                            });
                            resData.specialProcessesList.forEach((x) => {
                                delete x.id;
                            });
                            resData.orderDate = formatDate(Date.now());
                            delete resData.id;
                        }
                        this.ruleForm = resData;

                        // console.log(this.ruleForm, 'this.ruleForm');

                        this.tableData = resData.varietyYarnSpecItemList;
                        this.$nextTick(() => {
                            // this.$refs.orderBatchList.batchTabActive = '0';
                            // 更新关联通知单
                            this.$refs.noticeListPopoverBar.getListRequest();
                            this.$refs.foreNoticeListPopoverBar.getListRequest();
                        });
                    }
                }
            );
        },
        getTechnologyItemListRequest() {
            if (!this.ruleForm.processId) return;
            /* spinSpecParamPage({ auditState: 1, processId: this.ruleForm.processId }).then(res => {
                if (res.data.status === 200) {
                    this.tableData = res.data.res.map(x => {
                        return {
                            dataType: x.dataType,
                            specParamId: x.id,
                            ifBusi: x.ifBusi,
                            ifNull: x.ifNull,
                            ifWarning: x.ifWarning,
                            iotIdentifier: x.iotIdentifier,
                            specParamCode: x.code,
                            specParamName: x.name,
                            paramType: x.paramType,
                            val: null,
                            valMax: null,
                            valMin: null
                        };
                    });
                }
            });*/
        },
        onSelectYarnChange(e) {
            if (e) {
                this.tableData =
                    this.varietyYarnSpecList.find((x) => x.id === e)
                        .varietyYarnSpecItemList || [];
            } else {
                this.tableData = [];
            }
        },
        getYarnListRequest() {
            return spinVarietyYarnSpecPage({ auditState: 1 }).then((res) => {
                if (res.data.status === 200) {
                    this.varietyYarnSpecList = res.data.res;
                    if (res.data.res && !this.dataId) {
                        const item =
                            this.varietyYarnSpecList.find(
                                (x) => x.code === 'ZJSGY'
                            ) || {};
                        this.$set(this.ruleForm, 'varietyYarnSpecId', item.id);
                        this.$set(
                            this.ruleForm,
                            'varietyYarnSpecCode',
                            item.code
                        );
                        this.$set(
                            this.ruleForm,
                            'varietyYarnSpecName',
                            item.name
                        );
                        this.tableData = item.varietyYarnSpecItemList || [];
                    }
                }
            });
        },
        // 批量获取销售订单详情
        getSaleOrderDetailByIdsRequest() {
            return productionSaleOrderGetIds({
                ids: this.$route.query.saleOrderProductIds.split(',')
            }).then((res) => {
                if (res.data.status === 200) {
                    let arr = res.data.res || [];
                    arr = arr.map((x) => this.getSaleOrderItemInfo(x));
                    if (!this.ruleForm.productOrderSaleList) {
                        this.ruleForm.productOrderSaleList = [];
                    }
                    const unHasArr = arr.filter(
                        (x) =>
                            !this.ruleForm.productOrderSaleList
                                .map((k) => k.saleOrderItemId)
                                .includes(x.saleOrderItemId)
                    );

                    let qty = 0;
                    unHasArr.forEach((x) => {
                        qty = mathJsAdd(qty, x.orderAllocatedQty || 0);
                        this.ruleForm.productOrderSaleList.push(x);
                    });

                    // 只有一个排产中的批号时，将下达的量累加到该批号身上
                    let count = 0;
                    if (this.ruleForm.productOrderBatchList) {
                        this.ruleForm.productOrderBatchList.forEach(
                            (batchItem) => {
                                if (
                                    batchItem.orderBatchPrdNotice.auditState !==
                                    3
                                ) {
                                    count++;
                                }
                            }
                        );
                        if (count && count === 1) {
                            this.ruleForm.productOrderBatchList.forEach(
                                (batchItem) => {
                                    if (
                                        batchItem.orderBatchPrdNotice
                                            .auditState !== 3
                                    ) {
                                        this.$set(
                                            batchItem.orderBatchPrdNotice,
                                            'productionQty',
                                            mathJsAdd(
                                                batchItem.orderBatchPrdNotice
                                                    .productionQty || 0,
                                                qty
                                            )
                                        );
                                    }
                                }
                            );
                        }
                    }
                    const productInfo = arr.length ? arr[0] : {};
                    this.setProductDependentData(
                        JSON.parse(JSON.stringify(productInfo))
                    );
                    this.calSaleOrderTotalQty();
                }
            });
        },
        getDemoYarnState() {
            if (this.demoYarnInfo) {
                const orderQty = this.ruleForm.orderQty || 0;
                const minVal = this.demoYarnInfo.minValue / 1000;
                const maxVal = this.demoYarnInfo.maxValue / 1000;
                this.isDemoYarn = orderQty >= minVal && orderQty <= maxVal;
            }
        },
        getDemoYarnInfoRequest() {
            return productionTestProductConfigPage().then((res) => {
                if (res.data.status === 200) {
                    this.demoYarnInfo =
                        res.data.res && res.data.res.length
                            ? res.data.res[0]
                            : null;
                    this.getDemoYarnState();
                }
            });
        },
        async getDependentData() {
            this.showContentLoading = true;
            await this.getSpinSpecPathListRequest();
            await this.getTypeListRequest();
            this.dataId = this.$route.query.id
                ? Number(this.$route.query.id)
                : null;

            if (this.pageType !== 'detail') {
                this.workshopList =
                    this.$store.state.user.userWorkshop.workshopList;
                if (!this.dataId) {
                    this.$set(this.ruleForm, 'priorityId', 0);
                    this.$set(
                        this.ruleForm,
                        'plannerId',
                        this.$store.state.user.empInfo.id
                    );
                    this.$set(
                        this.ruleForm,
                        'plannerName',
                        this.$store.state.user.empInfo.name
                    );
                    this.$set(
                        this.ruleForm,
                        'workshopId',
                        this.$store.state.user.userWorkshop.defaultWorkshopId
                    );
                    this.$set(
                        this.ruleForm,
                        'workshopCode',
                        this.$store.state.user.userWorkshop.defaultWorkshopCode
                    );
                    this.$set(
                        this.ruleForm,
                        'workshopName',
                        this.$store.state.user.userWorkshop.defaultWorkshopName
                    );
                    this.$set(
                        this.ruleForm,
                        'orderDate',
                        formatDate(Date.now())
                    );
                    this.$set(
                        this.ruleForm,
                        'deliveryDateFrom',
                        formatDate(Date.now())
                    );
                    this.$set(
                        this.ruleForm,
                        'deliveryDateTo',
                        formatDate(Date.now() + 7 * 24 * 60 * 60 * 1000)
                    );
                }
                // if (this.$route.query.saleOrderProductIds) await this.getSaleOrderDetailByIdsRequest();
                await this.getYarnListRequest();
            }
            if (this.dataId) await this.getDetailRequest();
            if (this.$route.query.saleOrderProductIds) {
                await this.getSaleOrderDetailByIdsRequest();
            }
            await this.getDemoYarnInfoRequest();
            this.$nextTick(() => {
                this.$refs.ruleForm.clearValidate();
            });

            this.showContentLoading = false;
        },
        clearCacheMethod() {
            Object.assign(this.$data, this.$options.data());
            // this.$refs.orderBatchList.batchTabActive = '0';
            this.$nextTick(() => {
                this.$refs.ruleForm.clearValidate();
                this.getDependentData();
            });
        }
    },
    watch: {
        ruleForm: {
            handler() {
                this.getDemoYarnState();
            },
            deep: true,
            immediate: true
        }
    }
};
